﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Xml.Linq;
using System.Web.Routing;
using System.Web.DynamicData;
using Icst.Leaflike.Data;
using Icst.Leaflike.Logging;

namespace Icst.Leaflike.Web
{
    public class Global : System.Web.HttpApplication
    {
        protected void Application_Start(object sender, EventArgs e)
        {
            InitLogger();
            RegisterRoutes(RouteTable.Routes);
            LoadSettings();

            Application.ClearUserCount();
        }
        protected void Session_Start(object sender, EventArgs e) 
        {
            Session.Timeout = AppConfig.sessiontimeout;
            Application.IncUserCount();
        }

        protected void Session_End(object sender, EventArgs e)          
        {
            Application.DecUserCount();
        }
        protected void Application_Error(Object sender, EventArgs e)
        {
            Exception ex = Server.GetLastError();
            Logger.Error("application error:" + ex.Message);
        }
        public static void RegisterRoutes(RouteCollection routes)
        {
            MetaModel model = new MetaModel();
            model.RegisterContext(typeof(leaflikeDataContext), new ContextConfiguration() { ScaffoldAllTables = true });
            model.DynamicDataFolderVirtualPath = "~/Admin/DynamicData/";
            routes.Add(new DynamicDataRoute("Admin/{table}/{action}.aspx")
            {
                Constraints = new RouteValueDictionary(new { action = "List|Details|Edit|Insert" }),
                Model = model,
            });
        }
        public static void LoadSettings()
        {
            Logger.Info("LOADING system settings..");
            SysSetting.Instance.ListAll();
            Logger.Info("SYSTEM SETTING LOADED.");
            Logger.Info("DNTAPIKey=" + AppConfig.DNTAPIKey);
            Logger.Info("DNTSecert=" + AppConfig.DNTSecert);
            Logger.Info("DNTWebServer=" + AppConfig.DNTWebServer);
        }
        private void InitLogger()
        {
            string configFile = Server.MapPath("~/log4net.config");
            Logger.Initialize(configFile);
        }
    }
}
